<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
			<!--采购单信息-->
			<view class="detail-item">
				<uni-section title="采购单信息" type="line"></uni-section>
				<view class="detail-content">
					<view class="detail-text">
						采购单号：
						<text>{{info.number}}</text>
						<text class="detail-text-copy" @click.stop="copyText(info.number)">复制</text>
					</view>
					<view class="detail-text">
						关联采购需求单：
						<text>{{info.demandNumber}}</text>
						<text class="detail-text-copy" @click.stop="copyText(info.demandNumber)">复制</text>
					</view>
					<view class="detail-text">
						制单人员：
						<text>{{info.createUserName}}</text>
					</view>
					<view class="detail-text">
						仓库名称：
						<text>{{info.warehouseName}}</text></view>
					<view class="detail-text">
						采购人员：
						<text>{{info.purchaseUserName}}</text></view>
					<view class="detail-text">
						供应商：
						<text>{{info.supplierName}}</text></view>
					<view class="detail-text">
						下单时间：
						<text>{{info.createTime}}</text></view>
					<view class="detail-text">
						仓库地址：
						<text>{{warehouseInfo.addr}}</text></view>
					<view class="detail-text">
						入库时间：
						<text>{{info.storageInCreateTime}}</text></view>
					<view class="detail-text" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">
						其他金额：
						<text>{{info.otherPrice}}</text></view>
					<view class="detail-text" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">
						优惠金额：
						<text>{{info.discountPrice}}</text></view>
					<view class="detail-text" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">
						采购金额：
						<text>{{info.allPrice}}</text></view>
					<view class="detail-text">
						采购状态：
						<uni-tag size="small" :text="arrText(purchaseOrderStatusList, info.status)" /></view>
					<view class="detail-text">
						采购说明：
						<text>{{info.remark}}</text></view>
				</view>
			</view>
			<!--采购商品信息-->
			<view class="detail-item">
				<uni-section title="采购商品信息" type="line"></uni-section>
				<view class="detail-content">
					<ty-table
						:data="tableList"
						:columns="columns"
						:sortable="true"
						:cellClassName="() => 'table-cell'"
						:headerCellClassName="() => 'table-cell'"
						stripe
						border>
						<template v-slot:left="{ row }">
							<view class="table-td-cell">
								<view class="table-td-row">
									名称：
									<text class="table-td-text">{{row.productName}}</text></view>
								<view class="table-td-row">
									单位：
									<text class="table-td-text">{{row.unit}}</text></view>
							</view>
						</template>
						
						<template v-slot:center="{ row }">
							<view class="table-td-cell">
								<view class="table-td-row">
									数量：
									<text class="table-td-text">{{row.purchaseNumber}}</text></view>
								<view class="table-td-row" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">
									价格：
									<text class="table-td-text">{{row.purchasePrice}}</text></view>
								<view class="table-td-row" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">
									金额：
									<text class="table-td-text">{{row.subtotal}}</text></view>
							</view>
						</template>
						
						<template v-slot:right="{ row }">
							<view class="table-td-cell">
								<view class="table-td-row">
									生产日期：
									<text class="table-td-text">{{row.productionDate}}</text></view>
								<view class="table-td-row">
									过期时间：
									<text class="table-td-text">{{row.expireDate}}</text></view>
							</view>
						</template>
					</ty-table>
				</view>
			</view>
			<!--付款信息-->
			<view class="detail-item" v-if="info.payStatus === 1">
				<uni-section title="付款信息" type="line"></uni-section>
				<view class="detail-content">
					<view class="detail-text" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">
						付款金额：
						<text>{{info.payPrice}}</text></view>
					<view class="detail-text">
						付款时间：
						<text>{{info.payTime}}</text></view>
					<view class="main-flex detail-text detail-flex-start" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">
						付款截图：
						<view class="detail-text_r">
							<up-image width="120rpx" height="120rpx" @click.stop="previewImg(info.payImg)" :src="info.payImg" :lazy-load="true"></up-image>
						</view>
					</view>
					<view class="detail-text">
						付款说明：
						<text>{{info.payRemark}}</text></view>
				</view>
			</view>
			
		</view>
		
		<view class="detail-btns main-flex" v-if="info.id">
			
			<view v-if="checkPermi(['zhouyz:purchaseOrder:financeAudit']) && info.status === 7" class="detail-btn main-flex">
				<up-button
					class="detail-btn-info"
					type="primary"
					@click.stop="openFinanceAudit">
					<uni-icons class="table-operate-btn-icon" type="auth" size="14" color="#ffffff"></uni-icons>
					<view class="table-operate-btn-text">财务审核</view>
				</up-button>
			</view>
			
		</view>
		
		<!--财务审核-->
		<up-popup :z-index="90" round="5" closeable :show="showFinanceAudit" @close="financeAuditCancel" mode="center">
			<view class="edit">
				<view class="edit-header">财务审核</view>
				<view class="edit-form">
					<uni-forms
						ref="financeAuditRef"
						:modelValue="financeAuditModel"
						:rules="financeAuditRules"
						label-width="160rpx">
						<uni-forms-item label="付款金额" name="payPrice" required>
						  <uni-easyinput v-model="financeAuditModel.payPrice" placeholder="请输入付款金额" />
						</uni-forms-item>
						<uni-forms-item label="付款截图" name="payImg" required>
							<up-upload
								:fileList="fileList"
								@afterRead="afterRead"
								@delete="deletePic"
								:maxCount="1"
								></up-upload>
						  <uni-easyinput style="display: none;" v-model="financeAuditModel.payImg" placeholder="上传付款截图" />
						</uni-forms-item>
						<uni-forms-item label="付款说明" name="payRemark">
							<uni-easyinput type="textarea" v-model="financeAuditModel.payRemark" placeholder="请输入付款说明"></uni-easyinput>
						</uni-forms-item>
					</uni-forms>
					<view class="edit-footer main-flex">
						<up-button
							class="edit-footer-item"
							@click="financeAuditCancel"
							text="取消"></up-button>
						<up-button
							class="edit-footer-item"
							text="确认"
							type="primary"
							:disabled="isSubmit"
							:loading="isSubmit"
							@click="financeAuditConfirm"></up-button>
					</view>
				</view>
			</view>
		</up-popup>
		
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import { purchaseOrderDetail, purchaseOrder, saveFinanceAudit } from "@/api/erp_api/purchase"
import { purchaseOrderStatus } from "@/api/system/dict/data"
import { warehouseDetail } from "@/api/erp_api/warehouse"
import { copyText, previewImg, arrText } from '@/utils/ty.js'
import useUserStore from '@/store/modules/user'
import { upload } from "@/api/system/common"
import { timeFormat } from 'uview-plus'

	const userStore = useUserStore()
	onLoad(async (option) => {
		if (option.id) {
			await getPurchaseOrderStatus()
			id.value = option.id
			getDetail()
		}
	})
	
	// 采购状态
	const purchaseOrderStatusList = ref([])
	const getPurchaseOrderStatus = () => {
		return purchaseOrderStatus().then(res => {
			purchaseOrderStatusList.value = res.data.map(item => {
				return {
					...item,
					value: item.dictValue,
					text: item.dictValue == 3 ? '审核不通过/作废' : item.dictLabel
				}
			}) || []
		})
	}
	
	// 数据查询
	const id = ref('')
	const info = ref({})
	const isLoading = ref(false)
	
	const getDetail = () => {
		const params = {
			id: id.value
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		purchaseOrderDetail(params).then(res => {
			info.value = res.data || {}
			isLoading.value = false
			getWarehouse(res.data.warehouseId)
			getProduct(res.data.number)
			uni.hideLoading()
    }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	const warehouseInfo = ref({})
	const getWarehouse = (warehouseId) => {
		warehouseDetail({
			id: warehouseId
		}).then(res => {
			warehouseInfo.value = res.data
		})
	}
	
	// 表格头部
	const columns = ref([
		{ title: '名称单位', key: 'left' },
		{ title: '价格数量', key: 'center', width: '180rpx' },
		{ title: '生产日期', key: 'right', width: '250rpx' }
	])
	const tableList = ref([])
	const getProduct = (number) => {
		purchaseOrder({
			number 
		}).then(res => {
			tableList.value = res?.rows[0]?.productList || []
		})
	}
	
	const showFinanceAudit = ref(false)
	const financeAuditRef = ref(null)
	
	const financeAuditModel = ref({
		payImg: '',
		payPrice: '',
		payRemark: ''
	})
	const financeAuditRules = ref({
		payImg: {
			rules: [{ required: true, errorMessage: '请上传付款图片' }]
		},
		payPrice: {
			rules: [{ required: true, errorMessage: '请输入付款金额' }]
		}
	})
	// 图片上传
	const fileList = ref([])
	
	// 删除图片
	const deletePic = (event) => {
	  fileList.value.splice(event.index, 1)
		financeAuditModel.value.payImg = fileList.value.map(item => item.url).join(',')
	}
	
	// 新增图片
	const afterRead = async (event) => {
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file)
	  let fileListLen = fileList.value.length
	  lists.map((item) => {
	    fileList.value.push({
	      ...item,
	      status: 'uploading',
	      message: '上传中',
	    });
	  });
	  for (let i = 0; i < lists.length; i++) {
	    const result = await upload(lists[i].url)
			const data = JSON.parse(result.data)
	    let item = fileList.value[fileListLen]
	    fileList.value.splice(fileListLen, 1, {
	      ...item,
	      status: 'success',
	      message: '',
	      url: data.url,
	    });
	    fileListLen++;
	  }
		financeAuditModel.value.payImg = fileList.value.map(item => item.url).join(',')
	};
	
	const openFinanceAudit = () => {
		showFinanceAudit.value = true
	}
	const financeAuditCancel = () => {
		showFinanceAudit.value = false
		financeAuditModel.value.payImg = ''
		financeAuditModel.value.payPrice = ''
		financeAuditModel.value.payRemark = ''
		fileList.value = []
	}
	
	const isSubmit = ref(false)
	const financeAuditConfirm = () => {
		financeAuditRef.value.validate().then(formRes => {
			const params = { 
				...info.value,
				...formRes
			}
			isSubmit.value = true
			saveFinanceAudit(params).then(async (res) => {
				modal.showToast(res.msg)
				await uni.$u.sleep(1000)
				isSubmit.value = false
				financeAuditCancel()
				uni.$emit('refreshList');  // 触发刷新事件
				uni.navigateBack({
					delta: 1
				})
			}).catch(err => {
				isSubmit.value = false
			})
		})
	}
	
</script>

<style scoped lang="scss">
.detail-text-integral {
	margin-left: 20rpx;
}
.detail-text-banners {
	margin-left: -10rpx;
}
.detail-text-banner {
	margin: 0 10rpx 10rpx;
}
.detail-text-video {
	width: 100%;
	height: 250rpx;
}
</style>
